package com.pano.controal;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.pano.Enum.ResultMessage;
import com.pano.entity.Img;
import com.pano.entity.Scene;
import com.pano.service.ImgService;
import com.pano.service.SceneService;
import com.pano.service.VpoiService;

@RestController
@RequestMapping("/scene")
@SuppressWarnings("all")
public class SceneController extends BaseController {

	@Autowired
	private SceneService sceneService;
	@Autowired
	private ImgService imgService;
	
	/***
	 * 获取场景列表
	 * 
	 * @param vpoiid
	 * @return
	 */
	@RequestMapping(path = { "/query/{vpoiid}" }, method = { RequestMethod.GET, RequestMethod.POST })
	public Map query(@PathVariable int vpoiid) {
		List<Scene> list = sceneService.findByVpoiid(vpoiid);
		Map map = new HashMap();
		map.put("rows", list);
		return map;
	}

	/***
	 * 上传场景图片
	 * 
	 * @param vpoiid
	 * @return
	 */
	@RequestMapping(path = { "/upload/{vpoiid}" }, method = { RequestMethod.POST })
	public Map upload(@PathVariable int vpoiid, MultipartFile file) {
		Map map = new HashMap();
		try {
			Scene scene = new Scene();
			scene.setImgurl(UUID.randomUUID().toString());
			scene.setName("场景-" + scene.getImgurl().substring(scene.getImgurl().length() - 5, scene.getImgurl().length()));
			scene.setVpoiid(vpoiid);
			Img img = new Img();
			img.setData(file.getBytes());
			img.setUrl(scene.getImgurl());
			sceneService.save(scene,img);
			map = returnMap(ResultMessage.UPLOAD_SUCCESS);
		} catch (IOException e) {
			e.printStackTrace();
			map = returnMap(ResultMessage.UPLOAD_ERROR);
		}
		return map;
	}

	/***
	 * 获取场景图片
	 * 
	 * @param vpoiid
	 * @return
	 */
	@RequestMapping(path = { "/read/{imgurl}" }, method = { RequestMethod.GET, RequestMethod.POST })
	public void read(HttpServletResponse res, @PathVariable String imgurl) {
		Img img = imgService.findByUrl(imgurl);
		try {
			OutputStream out = res.getOutputStream();
			res.setContentType("application/octet-stream");
			out.write(img.getData());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
